<template>
  <div class="upload-file">
    <!-- 上传对话框 -->
    <el-dialog v-if="upload.open" :title="upload.title" v-model="upload.open" width="400px" append-to-body
      custom-class="dialogTable" :before-close="closeUpload">
      <p></p>
      <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload"
        :limit="limits" v-model:file-list="fileList" :on-change="handleChange" :on-error="handleUploadError"  :on-remove="handleRemove" :on-exceed="handleExceed" :on-success="handleUploadSuccess" :show-file-list="true" :headers="upload.headers"
        class="upload-demo" ref="uploads" :auto-upload="true" style="display: inline-block"
        :disabled="disabled" :fileType="fileType" drag>
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <!-- 上传提示 -->
          <div class="el-upload__tip text-center">
            <template v-if="showTip">
              请上传
              <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
              <template v-if="fileType.length != 0"> 格式为 <b style="color: #f56c6c">{{ fileType.join(",") }}</b>
              </template>
              的文件。导入多个文件时，文件名称需相同。支持上传多个文件。
              <span @click="fieldInfoVisible=true" style="color:#0D9AFF;cursor:pointer;">字段说明</span>
            </template>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="(fileList.length == 0) || uploadDisabled" @click="submitFileForm">确 定</el-button>
          <el-button @click="closeUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--字段说明-->
    <el-dialog title="字段说明" v-model="fieldInfoVisible">
      <div style="margin-left: 20px;margin-top: 20px;">
        应上传符合以下字段要求的shp文件集合.（文件集合必须包括.dbf、.prj、.shp、.shx、.cpg类型的文件）
      </div>
      <div style="margin-left: 20px;margin-top: 20px;">
        空间数据类型：面
        坐标系要求：GCS_China_Geodetic_Coordinate_System_2000（EPSG:4490）
      </div>
      <div style="padding:20px;">
        <el-table :data="fieldInfoData" stripe>
          <el-table-column property="number" label="序号" width="55"></el-table-column>
          <el-table-column property="type" label="数据类型" width="100"></el-table-column>
          <el-table-column property="require" label="是否必填" width="100"></el-table-column>
          <el-table-column property="name" label="数据名称" width="200"></el-table-column>
          <el-table-column property="example" label="数据说明"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { getListsShp } from '@/api/map/shpFile'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 500,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  },
  code: {
    type: String,
    default: '',
  },
  //是否显示上传文件弹窗
  showFileUploadBool: {
    type: Boolean,
    default: false
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits(['closeUpload','sureUploadFile']);
const number = ref(0);
const fileList = ref([]);
const loading = ref(false);
const dataList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const limits = ref(10);
const newFileList = ref([]);

const uploadDisabled = ref(true);
/*** 用户导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { token: "tokrn " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile", // 上传的图片服务器地址
});
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/attachment/uploadFile"); // 上传的图片服务器地址

const data = reactive({
  form: {
    attach: [],
    reportAttach: [],
  },
})
const { form } = toRefs(data);
watch(() => props.modelValue, val => {
  // debugger
  if (val) {

    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.attachId = item.attachId || new Date().getTime() + temp++;
      item.name = item.attachName;
      item.url = item.attachPath;
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
}, { deep: true, immediate: true });


// 打开空间数据上传
function submitFileForm () {
  let nameArr = [];
  fileList.value.forEach(item=>{
    const typeName = item.name.slice(item.name.lastIndexOf(".") + 1);
    nameArr.push(typeName)
  })
  if((nameArr.includes('shp'&&'dbf'&&'prj'&&'shx'&&'cpg'))){
    newFileList.value = [];
    let id = [];
    fileList.value.forEach(item => {
      id.push(item.attachId)
    })
    proxy.$modal.loading("正在解析文件，请稍候...");
    getListsShp({ typeCode: props.code, fileIds: id.join(',') }).then(res => {
      console.log("getListsShp");
      console.log(res.data);
      proxy.$modal.closeLoading();
      dataList.value = res.data;
      newFileList.value = fileList.value;
      emit('sureUploadFile', {dataList:res.data,fileList:fileList.value});
      closeUpload();
    }).catch(err => {
      proxy.$modal.closeLoading();
    });
  }else{
    proxy.$modal.msgError(`必须上传.dbf、.prj、.shp、.shx、.cpg类型的文件！ `);
  }
};

// 上传前校检格式和大小
function handleBeforeUpload (file) {
  proxy.$modal.loading("正在上传文件，请稍候...");

  if(!fileList.value.length){
     // 非第一次上传
     console.log(fileList.value,'校验数组');
    if(fileList.value.length){
      var falg =   fileList.value.some(item=>{
        const name = item.name.slice(0,item.name.lastIndexOf("."));
        const fileName = file.name.slice(0,file.name.lastIndexOf("."));
        console.log(name,fileName,'名称对比');
        if(name!=fileName){
          const uploadName = fileList.value[0].name.slice(0,fileList.value[0].name.lastIndexOf("."));
          proxy.$modal.msgError(`文件名称不正确, 请上传名称为${uploadName}的文件!`);
          return true;
        }
      })
      if(falg){ return false;}
      var falg1 =   fileList.value.some(item=>{
        const typeName  = item.name.slice(item.name.lastIndexOf(".") + 1);
        const typeFileName = file.name.slice(file.name.lastIndexOf(".") + 1)
        if(typeFileName.includes('shp')||typeFileName.includes('prj')||typeFileName.includes('prj')||typeFileName.includes('shx')||typeFileName.includes('cpg')){
          if((typeName=='shp'&&typeFileName==typeName)||(typeName=='prj'&&typeFileName==typeName)||(typeName=='prj'&&typeFileName==typeName)||(typeName=='shx'&&typeFileName==typeName)||(typeName=='cpg'&&typeFileName==typeName)){
            proxy.$modal.msgError(`该类型文件只能上传一个!`);
            return true;
          }
        }
      })
      if(falg1){return false;}
    }
  }
  
  // 校检文件大小
  if (props.fileSize) {
    var isLt = file.size / 1024 / 1024 < 500;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过500MB!`);
      return false;
    }
  }
  upload.isUploading = true;
  number.value++;
  return true;
}

function handleChange (file, fileList) {
  fileList.value = fileList;
}

// 文件个数超出
function handleExceed () {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError (err) {
  proxy.$modal.closeLoading();
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess (res, file) {
  if (res.code == 200) {
    fileList.value.forEach(item=>{
      item.attachId =  item.response?.data[0].attachId,
      item.name = item.response?.data[0].attachName,
      item.url= item.response?.data[0].attachPath
    })
    proxy.$modal.closeLoading();
    proxy.$modal.msgSuccess("上传文件成功");
    let nameArr = [];
    fileList.value.forEach(item=>{
      let typeName = item.name?.slice(item.name.lastIndexOf(".") + 1);
      nameArr.push(typeName)
    })
    console.log(nameArr,'nameArr');
    // 检查是否所有必需的文件类型都已上传
    if (nameArr.includes('shp') && nameArr.includes('dbf') && nameArr.includes('prj') && nameArr.includes('shx') && nameArr.includes('cpg')) {
      uploadDisabled.value = false;
    } else {
      uploadDisabled.value = true;
    }
  }else {
    proxy.$modal.msgError("上传文件失败。");
    proxy.$modal.closeLoading();
  }
}

// 删除文件
function handleRemove (file, uploadFiles) {
  if(file.response.code==200){
    const index = fileList.value.findIndex(item => item.attachId === file.response?.data[0].attachId)
    fileList.value.splice(index, 1)
  }else{
    fileList.value=fileList.value.filter(item => item.response.code == 200)
  }
}
// 下载文件
function handleDownload (file) {
  var query = {
    attachId: file.attachId,
    name: file.attachName
  }
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId=" + encodeURIComponent(query.attachId);
}

//关闭上传文件窗口
const closeUpload = ()=>{
  upload.open = false;
  emit('closeUpload', true);
}

const fieldInfoVisible = ref(false);
//字段说明
const fieldInfoData = ref([
  {number: "1", type: "文本型", require: "否", name: "事件ID", example: "非必填，可为空值"},
  {number: "2", type: "浮点型", require: "是", name: "面积", example: "单位：平方米；示例：75512431.11"},
  {number: "3", type: "文本型", require: "否", name: "地震烈度（全名）", example: "示例：Ⅵ度（6度）"},
  {number: "4", type: "文本型", require: "否", name: "地震烈度（罗马数字）", example: "范围：罗马数字（Ⅵ、Ⅶ、Ⅷ、Ⅸ、Ⅹ、Ⅺ、Ⅻ）；示例：Ⅵ"},
  {number: "5", type: "文本型", require: "是", name: "地震烈度（数字）", example: "数值范围：（6、7、8、9、10、11、12）；示例：6"},
]);

//是否显示上传文件弹窗
watch(() => props.showFileUploadBool, val => {
  upload.open = val;
  if (val) {
    fileList.value = [];
  }
});

defineExpose({
  fileList
});
</script>

<style scoped lang="scss">
// .upload-file {
//   width: 100%;
// }

.upload-demo {
  width: 100%;
  margin-bottom: 5px;
}

// .upload-file-list .el-upload-list__item {
//   border: 1px solid #e4e7ed;
//   line-height: 2;
//   margin-bottom: 10px;
//   position: relative;
// }

// .upload-file-list .ele-upload-list__item-content {
//   display: flex;
//   justify-content: space-between;
//   align-items: center;
//   color: inherit;
// }

// .ele-upload-list__item-content-action .el-link {
//   margin-right: 10px;
// }
:deep(.el-upload-list__item){
  .el-upload-list__item-info{
    .el-upload-list__item-name{
      display: block;
      white-space: pre-wrap!important;
      overflow: hidden;
      // text-overflow: ellipsis;
      max-width: 340px; /* 根据需要调整宽度 */
      cursor: pointer;
      padding: 0 20px 0 4px!important;
    }
  }  
}
</style>
